

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <title>Integrating Python and QML &mdash; PyQt 4.9.1 Reference Guide</title>
    
    <link rel="stylesheet" href="_static/default.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
    
    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
        URL_ROOT:    '',
        VERSION:     '4.9.1',
        COLLAPSE_INDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  true
      };
    </script>
    <script type="text/javascript" src="_static/jquery.js"></script>
    <script type="text/javascript" src="_static/underscore.js"></script>
    <script type="text/javascript" src="_static/doctools.js"></script>
    <link rel="shortcut icon" href="_static/logo_tn.ico"/>
    <link rel="top" title="PyQt 4.9.1 Reference Guide" href="index.html" />
    <link rel="next" title="Integrating Python and JavaScript in QtWebKit" href="webkit.html" />
    <link rel="prev" title="Support for QSettings" href="qsettings.html" /> 
  </head>
  <body>
    <div class="related">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="webkit.html" title="Integrating Python and JavaScript in QtWebKit"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="qsettings.html" title="Support for QSettings"
             accesskey="P">previous</a> |</li>
        <li><a href="index.html">PyQt 4.9.1 Reference Guide</a> &raquo;</li> 
      </ul>
    </div>  

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body">
            
  <div class="section" id="integrating-python-and-qml">
<h1>Integrating Python and QML<a class="headerlink" href="#integrating-python-and-qml" title="Permalink to this headline">¶</a></h1>
<p>Qt v4.7 introduced QML as a means of declaratively describing a user interface
and using JavaScript as a scripting language within QML.  It is possible to
write complete standalone QML applications, or to combine them with C++.</p>
<p>PyQt supports the integration of Python and QML as far as it can - given the
limitations of the QML implementation.</p>
<p>There are three types of QML application:</p>
<ul class="simple">
<li><em>Pure</em> applications that are written entirely in QML and can be run using the
<strong class="program">qmlviewer</strong> tool provided with Qt.  PyQt fully supports this type of
application.  The examples provided by <strong class="program">qtdemo.py</strong> under the <em>Qt
Declarative Examples</em> heading are all of this type.</li>
<li>QML allows <tt class="docutils literal"><span class="pre">QObject</span></tt> instances to be used in QML applications.  QML code is
able to call an object&#8217;s slots and has read and write access to the object&#8217;s
properties.  QML code can also respond to changes to the value of a property.
PyQt fully supports the use objects created in Python in this way.  The
<strong class="program">minehunt.py</strong> example under the <em>Demonstrations</em> heading of
<strong class="program">qtdemo.py</strong> is an example of this type of application.</li>
<li>QML also allows <tt class="docutils literal"><span class="pre">QObject</span></tt> sub-classes to be used in QML applications so
that new instances are created from QML.  PyQt does not support this.  The
reason is that QML uses information generated at compile time (specifically
it uses <tt class="docutils literal"><span class="pre">QObject::staticMetaObject</span></tt>) rather than information created
dynamically at run time (i.e. <tt class="docutils literal"><span class="pre">QObject::metaObject()</span></tt>).  This approach is
fine for a static language like C++ but causes problems for languages such as
Python that allow types to created dynamically.  This limitation doesn&#8217;t
place any restriction on the functionality of a Python/QML application, it
only places restrictions on how that application is written.</li>
</ul>
<p>QML can implement JavaScript functions and define signals.  PyQt allows both of
these to be accessed transparently from Python.  The following is a simple
example application that displays the current date and time when the user
clicks on it.</p>
<p>The following is the QML (in the <tt class="file docutils literal"><span class="pre">message.qml</span></tt>) that defines the user
interface:</p>
<div class="highlight-python"><pre>import Qt 4.7

Rectangle {
    signal messageRequired;

    function updateMessage(text) {
        messageText.text = text
    }

    anchors.fill: parent; color: "black"

    Text {
        id: messageText
        anchors.centerIn: parent; color: "white"
    }

    MouseArea {
        anchors.fill: parent
        onClicked: messageRequired()
    }
}</pre>
</div>
<p>This defines a signal <tt class="docutils literal"><span class="pre">messageRequired</span></tt> which is emitted when the user clicks
on the mouse area.  It also implements a function <tt class="docutils literal"><span class="pre">updateMessage()</span></tt> which
updates the message being displayed.</p>
<p>The following is the Python code that implements the application logic:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">sys</span>

<span class="kn">from</span> <span class="nn">PyQt4.QtCore</span> <span class="kn">import</span> <span class="n">QDateTime</span><span class="p">,</span> <span class="n">QObject</span><span class="p">,</span> <span class="n">QUrl</span><span class="p">,</span> <span class="n">pyqtSignal</span>
<span class="kn">from</span> <span class="nn">PyQt4.QtGui</span> <span class="kn">import</span> <span class="n">QApplication</span>
<span class="kn">from</span> <span class="nn">PyQt4.QtDeclarative</span> <span class="kn">import</span> <span class="n">QDeclarativeView</span>


<span class="c"># This class will emit the current date and time as a signal when</span>
<span class="c"># requested.</span>
<span class="k">class</span> <span class="nc">Now</span><span class="p">(</span><span class="n">QObject</span><span class="p">):</span>

    <span class="n">now</span> <span class="o">=</span> <span class="n">pyqtSignal</span><span class="p">(</span><span class="nb">str</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">emit_now</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="n">formatted_date</span> <span class="o">=</span> <span class="n">QDateTime</span><span class="o">.</span><span class="n">currentDateTime</span><span class="p">()</span><span class="o">.</span><span class="n">toString</span><span class="p">()</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">now</span><span class="o">.</span><span class="n">emit</span><span class="p">(</span><span class="n">formatted_date</span><span class="p">)</span>


<span class="n">app</span> <span class="o">=</span> <span class="n">QApplication</span><span class="p">(</span><span class="n">sys</span><span class="o">.</span><span class="n">argv</span><span class="p">)</span>

<span class="n">now</span> <span class="o">=</span> <span class="n">Now</span><span class="p">()</span>

<span class="c"># Create the QML user interface.</span>
<span class="n">view</span> <span class="o">=</span> <span class="n">QDeclarativeView</span><span class="p">()</span>
<span class="n">view</span><span class="o">.</span><span class="n">setSource</span><span class="p">(</span><span class="n">QUrl</span><span class="p">(</span><span class="s">&#39;message.qml&#39;</span><span class="p">))</span>
<span class="n">view</span><span class="o">.</span><span class="n">setResizeMode</span><span class="p">(</span><span class="n">QDeclarativeView</span><span class="o">.</span><span class="n">SizeRootObjectToView</span><span class="p">)</span>

<span class="c"># Get the root object of the user interface.  It defines a</span>
<span class="c"># &#39;messageRequired&#39; signal and JavaScript &#39;updateMessage&#39; function.  Both</span>
<span class="c"># can be accessed transparently from Python.</span>
<span class="n">rootObject</span> <span class="o">=</span> <span class="n">view</span><span class="o">.</span><span class="n">rootObject</span><span class="p">()</span>

<span class="c"># Provide the current date and time when requested by the user interface.</span>
<span class="n">rootObject</span><span class="o">.</span><span class="n">messageRequired</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="n">now</span><span class="o">.</span><span class="n">emit_now</span><span class="p">)</span>

<span class="c"># Update the user interface with the current date and time.</span>
<span class="n">now</span><span class="o">.</span><span class="n">now</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="n">rootObject</span><span class="o">.</span><span class="n">updateMessage</span><span class="p">)</span>

<span class="c"># Provide an initial message as a prompt.</span>
<span class="n">rootObject</span><span class="o">.</span><span class="n">updateMessage</span><span class="p">(</span><span class="s">&quot;Click to get the current date and time&quot;</span><span class="p">)</span>

<span class="c"># Display the user interface and allow the user to interact with it.</span>
<span class="n">view</span><span class="o">.</span><span class="n">setGeometry</span><span class="p">(</span><span class="mi">100</span><span class="p">,</span> <span class="mi">100</span><span class="p">,</span> <span class="mi">400</span><span class="p">,</span> <span class="mi">240</span><span class="p">)</span>
<span class="n">view</span><span class="o">.</span><span class="n">show</span><span class="p">()</span>

<span class="n">app</span><span class="o">.</span><span class="n">exec_</span><span class="p">()</span>
</pre></div>
</div>
<p>Hopefully the comments in the code are sufficient explanation.  The important
things to note are that the signal and JavaScript function appear as
appropriate attributes of the root object <tt class="docutils literal"><span class="pre">QDeclarativeItem</span></tt> returned by the
<tt class="docutils literal"><span class="pre">rootObject()</span></tt> method of <tt class="docutils literal"><span class="pre">QDeclarativeView</span></tt> and can be connected to and
called respectively.</p>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar">
        <div class="sphinxsidebarwrapper">
            <p class="logo"><a href="index.html">
              <img class="logo" src="_static/logo.png" alt="Logo"/>
            </a></p>
  <h4>Previous topic</h4>
  <p class="topless"><a href="qsettings.html"
                        title="previous chapter">Support for QSettings</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="webkit.html"
                        title="next chapter">Integrating Python and JavaScript in QtWebKit</a></p>
<div id="searchbox" style="display: none">
  <h3>Quick search</h3>
    <form class="search" action="search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    <p class="searchtip" style="font-size: 90%">
    Enter search terms or a module, class or function name.
    </p>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>
    <div class="related">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="webkit.html" title="Integrating Python and JavaScript in QtWebKit"
             >next</a> |</li>
        <li class="right" >
          <a href="qsettings.html" title="Support for QSettings"
             >previous</a> |</li>
        <li><a href="index.html">PyQt 4.9.1 Reference Guide</a> &raquo;</li> 
      </ul>
    </div>
    <div class="footer">
        &copy; Copyright 2011 Riverbank Computing Limited.
      Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.1.2.
    </div>
  </body>
</html>